use diesel::{Connection, PgConnection};

use crate::{
  mappers::{person::PersonMapper, role::RoleMapper},
  models::person::NewPerson,
};

// 获取到数据库连接对象
fn get_db_connection() -> PgConnection {
  // 读取 docker-compose.yml 中配置的 DATABASE_URL 属性值
  let database_url =
    std::env::var("DATABASE_URL").expect("Cannot load DB url from env.");

  PgConnection::establish(&database_url)
    .expect("Cannot connect to Postgres DB.")
}

pub fn create_person(
  username: String,
  password: String,
  role_codes: Vec<String>,
) {
  let new_person = NewPerson { username, password };

  let mut conn = get_db_connection();

  let person = PersonMapper::create(&mut conn, new_person, role_codes).unwrap();
  println!("Person created. {:?}", person);

  let roles = RoleMapper::find_by_person(&mut conn, &person).unwrap();
  println!("Roles assigned. {:?}", roles);
}

pub fn list_persons() {}

pub fn delete_person(_id: i32) {}
